package com.inno.subject.domain.strategy.ai;

import com.inno.subject.common.enums.MockTypeEnum;
import com.inno.subject.domain.entity.InterviewBO;
import com.inno.subject.domain.utils.ApplicationContextUtil;
import com.inno.subject.domain.utils.ChatClientUtil;
import com.inno.subject.domain.websocket.SubjectSocket;
import jakarta.annotation.Resource;
import jakarta.websocket.Session;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 小程序端不存在不同类型 新增一个处理器适配通用的模拟面试功能
 * @author sean
 */
@Component
public class CommonInterviewHandler implements InterviewMockHandler{
    private static final String COMMON_QUESTION = "你是一位人力资源总监以及技术总监,在多个行业都有极其丰富的经验，现在我要来你们公司面试，你需要根据我的自我介绍，或简历内容，来对我进行一些提问，并且点评我的自我介绍，你需要百般刁难我，您只需要提问，由我来回答问题，您只需要判断我的回答是否正确，如果正确您再提问下一题，您每次提问一道题或二道题即可，并且当我问您今天的面试结果是否通过的时候，您需要根据我所答问题的表现，来判断是否可以通过。好的，现在开始面试了 : \t\t";
    @Resource
    private ThreadPoolTaskExecutor subjectExecutor;
    @Resource
    private ChatClientUtil chatClientUtil;
    @Override
    public String getType() {
        return MockTypeEnum.COMMON.getType();
    }

    @Override
    public void handle(InterviewBO interviewBO) {
        String keyword = MockTypeEnum.COMMON.getKeyword();

        subjectExecutor.submit(()-> this.start(interviewBO,keyword,chatClientUtil,COMMON_QUESTION));
    }

    /**
     * 重写父类start方法   小程序端模拟面试不要引语部分
     */
    @Override
    public void start(InterviewBO interviewBO, String quotation, ChatClientUtil chatClientUtil, String systemMessage) {
        String message = interviewBO.getMessage();
        if (StringUtils.isBlank(message)){
            return;
        }
        SubjectSocket socket = ApplicationContextUtil.getWebSocket();
        Long currentUser = interviewBO.getCurrentUser();
        Session session = socket.getSession(currentUser);
        if (Objects.isNull(session) || !session.isOpen()){
            return;
        }
        List<String> finalList = new CopyOnWriteArrayList<>();
        chatClientUtil.streamingCall(message, systemMessage, currentUser).subscribe(
                response -> ChatClientUtil.processorSubscribe(response, finalList, socket, session),
                error -> socket.sendMessage(session, "服务器开小差了...，请稍后重试"),
                () -> {
                    String finalMessage = finalList.get(finalList.size() - 1);
                    chatClientUtil.addHistoryMessage(finalMessage, currentUser);

                }
        );
    }

}
